<?php


namespace App;


class CurlUtil
{
    public static function get($url, $headers = [], $returnTransfer = true, $notSSL = true, $timeout = 60) {
        request('GET', $url, $headers, $returnTransfer, $notSSL, $timeout);
    }

    public static function post($url, $data = null, $headers = [], $returnTransfer = true, $notSSL = true, $timeout = 60) {
        request('POST', $url, $data, $headers, $returnTransfer, $notSSL, $timeout);
    }

    public static function request($method, $url, $data = null, $headers = [], $returnTransfer = true, $notSSL = true, $timeout = 60) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);

        if (empty($method)) {
            $method = 'GET';
        }

        if (strtoupper($method) == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);

            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        // CURLOPT_RETURNTRANSFER 为 1，则 $output 为响应体内容字符串。
        if ($returnTransfer) {
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        }

        if ($notSSL) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}